<template>
  <div ref="chart1" :style="{ width: '100%', height: '100%' }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
// 引入接口
import { reqLineAPI } from '@/api/visual/index'

const chart1 = ref()
const { proxy } = getCurrentInstance() as any
const legend = ref([])
const title = ref()
const x = ref([])
const y = ref([])
// 发起请求的函数
const init = async () => {
  let res = await reqLineAPI()
  if (res.code === 200) {
    legend.value = res.data.legend
    title.value = res.data.title
    x.value = res.data.x
    y.value = res.data.y
  }
}
onMounted(() => {
  init().then(() => {
    // 获取挂载的组件实例
    const echarts = proxy.$ECharts
    //初始化挂载
    const echarts1 = echarts.init(chart1.value)
    //添加配置
    echarts1.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter: function (objs, index) {
          let obj = objs[0]
          return `${obj.name}<br/>${obj.marker}${obj.seriesName} : ${obj.value}元`
        },
      },
      grid: {
        top: '3%',
        left: '3%',
        right: '2%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'value',
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        axisLabel: {
          show: false,
        },
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        type: 'category',
        boundaryGap: true,
        inverse: true, //反向
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          margin: 18,
          formatter: function (value, index) {
            var ind = index + 1
            if (ind == 1) {
              return '{a|' + value + '}'
            } else if (ind == 2) {
              return '{b|' + value + '}'
            } else if (ind == 3) {
              return '{c|' + value + '}'
            } else {
              return '{d|' + value + '}'
            }
          },
          rich: {
            a: {
              color: '#fb4d4b',
            },
            b: {
              color: '#f39c12',
            },
            c: {
              color: '#00a65a',
            },
            d: {
              color: '#fff',
            },
          },
        },
        data: x.value,
      },
      series: [
        {
          name: '房源价格',
          barMaxWidth: '40%',
          type: 'bar',

          label: {
            normal: {
              show: true,
              position: 'insideLeft',
              formatter: '{c}',
              textStyle: {
                color: '#fff',
              },
            },
          },
          data: y.value,
        },
      ],
    })
    // 自适应
    window.onresize = function () {
      echarts1.resize()
    }
  })
})
</script>

<style lang="scss" scoped></style>
